/* eslint-disable n/no-process-exit */
import * as path from "node:path";
import * as ts from "typescript";

const configFile = ts.findConfigFile(
  import.meta.url,
  (filename) => filename === "jsconfig.json",
);
if (!configFile) {
  console.log("configFile is undefined");
  process.exit(1);
}
const config = ts.getParsedCommandLineOfConfigFile(configFile, undefined, {
  ...ts.sys,
  onUnRecoverableConfigFileDiagnostic: (d) => {
    d;
  },
});
if (!config) {
  console.log("jsconfig parse fail");
  process.exit(1);
}
/**
 * @param {string[]} fileNames
 * @param {ts.CompilerOptions} options
 */
function compile(fileNames, options) {
  const program = ts.createProgram(fileNames, options);
  const emitResult = program.emit(undefined, ts.sys.writeFile);

  // let allDiagnostics = ts
  //   .getPreEmitDiagnostics(program)
  //   .concat(emitResult.diagnostics);

  // allDiagnostics.forEach(diagnostic => {
  //   if (diagnostic.file && diagnostic.start) {
  //     let { line, character } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
  //     let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
  //     console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
  //   } else {
  //     console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
  //   }
  // });
  const sourceFile = program.getSourceFile(fileNames[0]);
  if (!sourceFile) {
    console.log("sourceFile is undefined");
    return;
  }
  console.log("has sourceFile");
  sourceFile.forEachChild((node) => {
    ts.forEachChild(node, (childNode) => {
      console.log("kind", ts.SyntaxKind[childNode.kind]);
    });
    // const jsDocArr = ts.getJSDocTags(node);
    // if ( jsDocArr.length){
    //   // console.log(jsDocArr);
    //   jsDocArr.forEach((jsdNode => {
    //     console.log("jsdNode.tagName", jsdNode.tagName.escapedText);
    //   }))
    // }
  });
  const allNode = ts.getJSDocTags(sourceFile);
  for (const node of allNode) console.log(node);
  for (let index = 0; index < allNode.length; index++) {
    const element = allNode[index];
    console.log(element.tagName);
    console.log(element.parent);
    console.log(element.flags);
    console.log(element.comment);
  }
  const exitCode = emitResult.emitSkipped ? 1 : 0;
  console.log(`Process exiting with code '${exitCode}'.`);
  process.exit(exitCode);
}

compile(process.argv.slice(2), {
  noEmitOnError: true,
  noImplicitAny: true,
  target: ts.ScriptTarget.ES2022,
  module: ts.ModuleKind.CommonJS,
});
